package com.gof.example.utils;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.util.Collections;

/**
 * Created with IntelliJ IDEA.
 * Created by zhiyuan on 2018/4/30 22:14.
 * haiming.fei@tongdun.cn
 */
public class XmlUtil {

    public static <T> T getBean(Class<T> cls) throws ParserConfigurationException, IOException, SAXException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//        Document document = builder.parse(XmlUtil.class.getClassLoader().getResourceAsStream("factory/config.xml"));
        Document document = builder.parse(XmlUtil.class.getResourceAsStream("/factory/config.xml"));
        NodeList nodeList = document.getElementsByTagName("factroy");
        String content = nodeList.item(0).getFirstChild().getNodeValue();
        Class aClass = Class.forName(content);
        T instance = (T) aClass.newInstance();
//        return instance.createImage();
        return instance;
    }

    public static Object getBean(String cls) throws ParserConfigurationException, IOException, SAXException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(XmlUtil.class.getResourceAsStream("/bridge/config.xml"));
        NodeList nodeList = document.getElementsByTagName("classname");

        String content;
        if ("report".equals(cls)) {
            content = nodeList.item(0).getFirstChild().getNodeValue();
        } else {
            content = nodeList.item(1).getFirstChild().getNodeValue();
        }

        Class aClass = Class.forName(content);
        Object instance = aClass.newInstance();
        return instance;
    }

    public static void main(String[] args) throws IOException {
        System.out.println(Collections.list(Thread.currentThread().getContextClassLoader().getResources("")));
        System.out.println(Collections.list(
                //底层c++实现, 为null
                Thread.currentThread().getContextClassLoader().getResources("/")
        ));
//        try {
//            XmlUtil.getBean();
//        } catch (ParserConfigurationException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } catch (SAXException e) {
//            e.printStackTrace();
//        } catch (ClassNotFoundException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        } catch (InstantiationException e) {
//            e.printStackTrace();
//        }
    }
}
